﻿using System;
using System.Linq;
using Elasticsearch.Net;
using ESoft.Extensions;
using Microsoft.Extensions.Options;
using Nest;

namespace ESoft.Elasticsearch
{
    public class EsService : IEsService
    {
        /// <summary>
        /// Linq查询的官方Client
        /// </summary>
        public IElasticClient ElasticLinqClient { get; set; }

        private readonly ElasticOptions elasticOptions;

        public EsService(IOptions<ElasticOptions> options)
        {
            elasticOptions = options.Value;
            var uris = elasticOptions.Url.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToList().ConvertAll(x => new Uri(x));
            var connectionPool = new StaticConnectionPool(uris);
            var settings = new ConnectionSettings(connectionPool)
                .RequestTimeout(TimeSpan.FromSeconds(elasticOptions.Timeout));
            if (elasticOptions.UserName.IsNotNullOrWhiteSpace())
            {
                settings = settings.BasicAuthentication(elasticOptions.UserName, elasticOptions.UserPassword);
            }
            this.ElasticLinqClient = new ElasticClient(settings);
        }
    }
}
